package mx.kolobok.noteeditor.ui.keymap.actions;

import mx.kolobok.noteeditor.Note;
import mx.kolobok.noteeditor.NoteManagerException;
import mx.kolobok.noteeditor.ui.list.NoteListModel;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.ActionEvent;
import java.io.IOException;

/**
 * User:  Nikita Belenkiy
 * Date: 30.05.11
 * Time: 20:09
 */
public class NewNoteFromClipboardAction extends AbstractAction{
    private NoteListModel noteListModel;

    public NewNoteFromClipboardAction(NoteListModel noteListModel) {
         super("New note from clipboard");
        this.noteListModel = noteListModel;
        putValue(Action.ACCELERATOR_KEY, Actions.NEW_NOTE_FROM_CLIPBOARD_KEYSTROKE);
        final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.addFlavorListener(new FlavorListener() {
            @Override
            public void flavorsChanged(FlavorEvent e) {
                Object source = e.getSource();
                setEnabled(((Clipboard) source).isDataFlavorAvailable(DataFlavor.stringFlavor));
            }
        });


    }

    @Override
    public void actionPerformed(ActionEvent e) {
        final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        try {
            String data = (String) clipboard.getData(DataFlavor.stringFlavor);
            Note newNote = noteListModel.createNewNote("Note title", data);
            newNote.touch();
        } catch (UnsupportedFlavorException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (NoteManagerException e1) {
            e1.printStackTrace();
        }
    }
}
